import React, {useRef, useState} from 'react';
import type {FormInstance} from 'antd';
import {Card, Result, Button, Descriptions, Divider, Alert, message, Modal, Image, Tag} from 'antd';
import {PageContainer} from '@ant-design/pro-layout';
import ProForm, {
  ProFormCascader,
  ProFormDatePicker,
  ProFormDependency, ProFormItem,
  ProFormSelect, ProFormText, ProFormTextArea, ProFormUploadButton, StepsForm
} from '@ant-design/pro-form';
import type {AccountApprove} from './data.d';
import styles from './style.less';
import {useRequest} from "@@/plugin-request/request";
import ProCard from "@ant-design/pro-card";
import {UploadFile} from "antd/es/upload/interface";
import {accountApprove, accountApproveSave} from "@/pages/Account/Approve/service";
import {
  checkCompanyName,
  checkCreditCode,
  loadCategory,
  loadArea,
  loadCity,
  loadProvince
} from "@/services/ant-design-pro/api";
import moment, {Moment} from 'moment';
import 'moment/locale/zh-cn';

// moment.locale("zh-cn")
// console.log(moment(), moment().isValid())
// console.log(moment("2019年09月26日", 'YYYY年MM月DD日'), moment("2019年09月26日", 'YYYY年MM月DD日').isValid())
const StepDescriptions: React.FC<{
  stepData: AccountApprove;
  bordered?: boolean;
}> = ({stepData, bordered}) => {
  return (
    <Descriptions column={1} bordered={bordered} labelStyle={{width: "110px"}}>
      <Descriptions.Item label="认证类型">
        {/*{stepData.typeStrList}*/}

        {stepData?.typeStrList?.map((name, index) => (
          <Tag key={name + index}>{name}</Tag>
        ))}
      </Descriptions.Item>
      <Descriptions.Item label="企业名称"> {stepData.enterpriseName}</Descriptions.Item>
      <Descriptions.Item label="信用代码"> {stepData.creditCode}</Descriptions.Item>
      <Descriptions.Item label="单位电话"> {stepData.businessPhone}</Descriptions.Item>
      <Descriptions.Item label="成立时间"> {stepData.foundingTime}</Descriptions.Item>
      <Descriptions.Item label="信用代码">
        <Image width={100} src={stepData.businessLicence}/>
      </Descriptions.Item>
      <Descriptions.Item label="经营范围"> {stepData.businessScope}</Descriptions.Item>
      <Descriptions.Item label="注册地址"> {stepData.registerAddress}</Descriptions.Item>
      {
        stepData.transportLicense ? <Descriptions.Item
          label="经营许可证号"> {stepData.transportLicense}</Descriptions.Item> : <></>
      }
      {
        stepData.licenceStartTime ? <Descriptions.Item
          label="有效期开始日期"> {stepData.licenceStartTime}</Descriptions.Item> : <></>
      }
      {
        stepData.licenceEndTime ? <Descriptions.Item
          label="有效期结束日期"> {stepData.licenceEndTime}</Descriptions.Item> : <></>
      }
    </Descriptions>
  );
};
const resultStatus = {
  "1": "info",
  "2": "success",
  "-1": "error",
}

const StepResult: React.FC<{
  stepData: AccountApprove;
  onFinish: () => Promise<void>;
}> = (props) => {

  let title = "提交成功";
  let subTitle = "企业认证申请已提交，请等待认证审核！";
  if (props.stepData.approve === 2) {
    title = "认证通过"
    subTitle = "恭喜您，企业已认证通过！"
  }
  if (props.stepData.approve === -1) {
    title = "认证失败"
    subTitle = "抱歉，您提交的企业信息没有认证通过！"
  }
  return (
    <Result
      status={resultStatus[props.stepData.approve]}
      title={title}
      subTitle={subTitle}
      extra={
        props.stepData.approve === -1 ? <>
          <Button type="primary" onClick={props.onFinish}>
            重新申请
          </Button>
        </> : null
      }
      className={styles.result}
    >
      {props.children}
    </Result>
  );
};

const Approve: React.FC<Record<string, any>> = () => {

  const {loading} = useRequest<{ data: AccountApprove }>(async () => {
    const msg = await accountApprove();
    let data = msg.data;
    if (data.areaCode) {
      let number = parseInt(data.areaCode);
      data.province = Math.floor(number / 10000);
      data.city = Math.floor(number / 100);
      // @ts-ignore
      data.areaCode = number;
    }
    if (data.businessLicence) {
      data.businessLicenceFile = [{
        url: data.businessLicence,
        name: '营业执照',
        status: 'done'
      }];
    }
    if (data.contactPersonIdA) {
      data.contactPersonIdAFile = [{
        url: data.contactPersonIdA,
        name: '联系人身份证正面',
        status: 'done'
      }];
    }
    if (data.contactPersonIdB) {
      data.contactPersonIdBFile = [{
        url: data.contactPersonIdB,
        name: '联系人身份证反面',
        status: 'done'
      }];
    }
    if (data.legalPersonIdA) {
      data.legalPersonIdAFile = [{
        url: data.legalPersonIdA,
        name: '法人身份证正面',
        status: 'done'
      }];
    }
    if (data.legalPersonIdB) {
      data.legalPersonIdBFile = [{
        url: data.legalPersonIdB,
        name: '法人身份证反面',
        status: 'done'
      }];
    }
    setStepData(data);
    if (data.approve !== 0) {
      setCurrent(2);
    }
    return msg;
  });
  const [stepData, setStepData] = useState<AccountApprove>();
  const [current, setCurrent] = useState(0);
  const formRef = useRef<FormInstance>();

  const [previewData, setPreviewData] = useState({
    visible: false,
    image: '',
    title: '',
  });
  const submitCheckFile = (values: AccountApprove, fileName: string, dataName: string, msg: string) => {
    let file = values[fileName][0];
    console.log(file)
    if (file.status !== 'done' || (file?.response && file?.response?.code !== 200)) {
      throw new Error(msg);
    }
    values[dataName] = file?.response?.data?.url || file.url;
  };
  const saveSubmit = async (values: AccountApprove) => {
    try {
      submitCheckFile(values, 'businessLicenceFile', 'businessLicence', "营业执照未上传")
      // submitCheckFile(values, 'legalPersonIdAFile', 'legalPersonIdA', "法人身份证正面未上传")
      // submitCheckFile(values, 'legalPersonIdBFile', 'legalPersonIdB', "法人身份证反面面未上传")
      // submitCheckFile(values, 'contactPersonIdAFile', 'contactPersonIdA', "联系人身份证正面未上传")
      // submitCheckFile(values, 'contactPersonIdBFile', 'contactPersonIdB', "联系人身份证反面面未上传")
    } catch ({message: msg}) {
      // @ts-ignore
      message.error(msg);
      return false;
    }
    setStepData(values);
    try {
      let msg = await accountApproveSave(values);
      console.log(msg)
      setStepData(msg.data);
    } catch (e) {
      return false;
    }
    return true;
  }

  function filter(inputValue: any, path: any) {
    // @ts-ignore
    return path.some(option => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1);
  }

  const uploadProps = {
    headers: {
      Authorization: `Bearer ${localStorage.getItem('token')}`
    },
    multiple: false,
    // @ts-ignore
    onChange: function ({file}) {
      if (file.status === 'done' && file.response.code !== 200) {
        file.status = "error"
      }
      if (file.status === 'done' && file.response.code === 200) {
        console.log(file, "=========")
        let data = file.response.data;
        if (data.hasOwnProperty("单位名称")) {
          formRef.current?.setFieldsValue({"enterpriseName": data['单位名称']});
        }
        if (data.hasOwnProperty("社会信用代码")) {
          formRef.current?.setFieldsValue({"creditCode": data['社会信用代码']});
        }
        if (data.hasOwnProperty("经营范围")) {
          formRef.current?.setFieldsValue({"businessScope": data['经营范围']});
        }
        if (data.hasOwnProperty("成立日期")) {
          formRef.current?.setFieldsValue({"foundingTime": moment(data['成立日期'], 'YYYY年MM月DD日')});
        }
        if (data.hasOwnProperty("地址")) {
          formRef.current?.setFieldsValue({"registerAddress": data['地址']});
        }
        if (data.hasOwnProperty("province")) {
          formRef.current?.setFieldsValue({"province": data['province']});
          formRef.current?.setFieldsValue({"city": undefined});
          formRef.current?.setFieldsValue({"areaCode": undefined});
        }
        if (data.hasOwnProperty("city")) {
          formRef.current?.setFieldsValue({"city": data['city']});
          formRef.current?.setFieldsValue({"areaCode": undefined});
        }
        formRef.current?.validateFields()
      }
    },
    onPreview: async (file: UploadFile) => {
      setPreviewData({
        image: file?.response?.data?.url || file.url,
        visible: true,
        title: "查看图片",
      });
    },
    name: 'file',
    listType: "picture-card",
    max: 1,
  };
  return (
    <PageContainer content="企业信息认证" waterMarkProps={{content: '企业信息认证', fontColor: "#ff000040"}}>
      {loading ? null : <Card bordered={false}>
        <StepsForm
          current={current}
          onCurrentChange={setCurrent}
          submitter={{
            render: (props, dom) => {
              if (props.step === 0) {
                return (
                  <div style={{textAlign: 'center', width: "100%"}}>
                    <Button type="primary" onClick={() => props.onSubmit?.()} shape={"round"} size={"large"}>
                      保存信息
                    </Button>
                  </div>
                );
              }

              if (props.step === 1) {
                return [
                  <Button key="pre" onClick={() => props.onPre?.()} shape={"round"} size={"large"}>
                    返回修改信息
                  </Button>,
                  <Button
                    type="primary"
                    key="goToTree"
                    onClick={() => props.onSubmit?.()} shape={"round"} size={"large"}>
                    提交认证
                  </Button>,
                ];
              }

              return [];
            },
          }}
        >
          <StepsForm.StepForm<AccountApprove>
            formRef={formRef}
            title="填写企业资料"
            initialValues={stepData}
            onFinish={saveSubmit}
            requiredMark={false}>

            <ProCard
              title="企业信息"
              bordered
              headerBordered
              style={{
                marginBottom: 16,
              }}>
              <ProFormCascader
                // @ts-ignore
                request={async () => {
                  return loadCategory().then(({data}) => {
                    return data;
                  });
                }}
                rules={[{required: true, message: '请选择认证类型'}]}
                fieldProps={{
                  multiple: true,
                  maxTagCount: 5,
                  showSearch: {filter: filter}
                }}
                name="typeList"
                label="认证类型"
              />
              <ProFormText name="enterpriseId" hidden></ProFormText>


              <ProFormUploadButton
                name="businessLicenceFile"
                label="营业执照"
                rules={[{required: true, message: '请上传营业执照'}]}
                max={1}
                // @ts-ignore
                fieldProps={{...uploadProps}}
                action="/v2/enterprise/upload/business-license"
                // extra="请上传营业执照,支持扩展名：.jpg, .jpeg, .png"
              />
              <ProFormText
                name="enterpriseName"
                label="企业名称"
                tooltip="请确保和营业执照上一致"
                hasFeedback={true}
                placeholder="请输入企业名称"
                rules={[
                  {required: true},
                  {
                    validator: async (rule, value) => {
                      if (value) {
                        let result = await checkCompanyName(value);
                        if (result.data !== '0') {
                          throw new Error('企业名称已存在');
                        }
                      }
                    }
                  }
                ]}
                // addonAfter={<a onClick={checkName}>检测</a>}
              />
              <ProForm.Group size={5}>

                <ProFormText
                  name="creditCode"
                  label={'统一信用代码'}
                  hasFeedback={true}
                  tooltip="请确保和营业执照上一致"
                  placeholder="请输入"
                  rules={[
                    {required: true},
                    {
                      validator: async (rule, value) => {
                        if (value) {
                          let result = await checkCreditCode(value);
                          console.log(result);
                          if (result.data !== '0') {
                            throw new Error('信用代码已存在');
                          }
                        }
                      }
                    }]}
                />

                <ProFormText
                  name="businessPhone"
                  label={'单位电话'}
                  hasFeedback={true}
                  placeholder="请输入"
                  rules={[{required: true}]}
                />
                <ProFormDatePicker name="foundingTime" label="成立时间"/>
              </ProForm.Group>
              <ProFormTextArea
                name="businessScope"
                label="经营范围"
                placeholder="请输入"
              />
              <ProForm.Group title="所在省市">
                <ProFormSelect
                  rules={[
                    {
                      required: true,
                      message: '请选择省份',
                    },
                  ]}
                  name="province"
                  fieldProps={
                    {
                      onChange: (a, b) => {
                        formRef.current?.setFieldsValue({"city": undefined, "areaCode": undefined})
                        formRef.current?.validateFields();
                      }
                    }
                  }
                  className={styles.item}
                  request={async () => {
                    return loadProvince().then(({data}) => {
                      return data.map((item) => {
                        return {
                          label: item.extName,
                          value: item.id,
                        };
                      });
                    });
                  }}
                />
                <ProFormDependency name={['province']}>
                  {({province}) => {
                    return (
                      <ProFormSelect
                        params={{
                          key: province,
                        }}
                        name="city"
                        rules={[
                          {
                            required: true,
                            message: '请选择城市',
                          },
                        ]}
                        disabled={!province}
                        fieldProps={
                          {
                            onChange: (a, b) => {
                              formRef.current?.setFieldsValue({"areaCode": undefined})
                              formRef.current?.validateFields();
                            }
                          }
                        }
                        className={styles.item}
                        request={async () => {
                          return loadCity(province || 0).then(({data}) => {
                            return data.map((item) => {
                              return {
                                label: item.extName,
                                value: item.id,
                              };
                            });
                          });
                        }}
                      />
                    );
                  }}
                </ProFormDependency>

                <ProFormDependency key={"city"} name={['city']}>
                  {({city}) => {
                    return (
                      <ProFormSelect
                        params={{
                          key: city,
                        }}
                        name="areaCode"
                        rules={[
                          {
                            required: true,
                            message: '请选择地区',
                          },
                        ]}
                        disabled={!city}
                        className={styles.item}
                        request={async () => {

                          return loadArea(city || 0).then(({data}) => {
                            return data.map((item) => {
                              return {
                                label: item.extName,
                                value: item.id,
                              };
                            });
                          });
                        }}
                      />
                    );
                  }}
                </ProFormDependency>
              </ProForm.Group>
              <ProFormText
                name="registerAddress"
                label="注册地址"
                placeholder="请输入"
                rules={[{required: true}]}
              />
              <ProFormText
                name="contactAddress"
                label="邮寄地址"
                placeholder="请输入"
              />


              <ProForm.Group size={5}>
                <ProFormText name="transportLicense" label="经营许可证号"/>
                <ProFormDatePicker name="licenceStartTime" label="有效期开始日期"/>
                <ProFormDatePicker name="licenceEndTime" label="有效期结束日期"/>

                {/*<ProFormDependency name={['licenceLongTime']}>*/}
                {/*  {({licenceLongTime}) => {*/}
                {/*    console.log(licenceLongTime)*/}
                {/*    return !licenceLongTime ? (*/}
                {/*      <ProFormDatePicker name="licenceStartTime" label="有效期开始日期"/>*/}
                {/*    ) : null;*/}
                {/*  }}*/}
                {/*</ProFormDependency>*/}
                {/*<ProFormSwitch name="licenceLongTime" label="长期"/>*/}

              </ProForm.Group>
            </ProCard>
            <ProCard
              title="法人信息"
              bordered
              headerBordered
              extra={<span style={{color: "#9b9b9b"}}>选填</span>}
              style={{
                marginBottom: 16,
              }}
            >

              <ProForm.Group>
                <ProFormText name="legalPerson" label="法人"/>
                <ProFormText name="legalPersonTel" label="法人电话"/>
              </ProForm.Group>

              <ProForm.Group>
                <ProForm.Item>
                  <ProFormUploadButton
                    name="legalPersonIdAFile"
                    label="法人身份证正面"
                    max={1}
                    // @ts-ignore
                    fieldProps={{...uploadProps}}
                    action="/v2/enterprise/upload/idcard"
                  />
                </ProForm.Item>

                <ProForm.Item>
                  <ProFormUploadButton
                    name="legalPersonIdBFile"
                    label="法人身份证反面"
                    max={1}
                    // @ts-ignore
                    fieldProps={{...uploadProps}}
                    action="/v2/enterprise/upload/idcard"
                  />
                </ProForm.Item>
              </ProForm.Group>

            </ProCard>
            <ProCard
              title="联系人信息"
              bordered
              headerBordered
              extra={<span style={{color: "#9b9b9b"}}>选填</span>}
              style={{
                marginBottom: 16,
              }}
            >
              <ProForm.Group>
                <ProFormText name="contactPerson" label="联系人"/>
                <ProFormText name="contactPersonTel" label="联系人电话"/>
                <ProFormText name="contactPersonId" label="联系人身份证号"/>
              </ProForm.Group>

              <ProForm.Group>
                <ProForm.Item>
                  <ProFormUploadButton
                    name="contactPersonIdAFile"
                    label="联系人身份证正面"
                    max={1}
                    // @ts-ignore
                    fieldProps={{...uploadProps}}
                    action="/v2/enterprise/upload/idcard"
                  />
                </ProForm.Item>
                <ProForm.Item>

                  <ProFormUploadButton
                    name="contactPersonIdBFile"
                    label="联系人身份证反面"
                    max={1}
                    // @ts-ignore
                    fieldProps={{...uploadProps}}
                    action="/v2/enterprise/upload/idcard"
                  />
                </ProForm.Item>
              </ProForm.Group>
            </ProCard>


          </StepsForm.StepForm>

          <StepsForm.StepForm<AccountApprove>
            title="确认企业资料"
            initialValues={stepData}
            onFinish={async () => {
              try {
                // @ts-ignore
                stepData.approve = 1;
                await accountApproveSave(stepData as AccountApprove);
              } catch (e) {
                return false;
              }
              return true;
            }}>
            <div className={styles.result}>
              <Alert
                closable
                showIcon
                message="请确认信息"
                style={{marginBottom: 24}}
              />
              <StepDescriptions stepData={stepData as AccountApprove} bordered/>
              <Divider style={{margin: '24px 0'}}/>
            </div>
          </StepsForm.StepForm>
          <StepsForm.StepForm<AccountApprove> title="完成">
            <StepResult
              stepData={stepData as AccountApprove}
              onFinish={async () => {
                setCurrent(0);
                formRef.current?.resetFields();
              }}
            >
              <StepDescriptions stepData={stepData as AccountApprove}/>
            </StepResult>
          </StepsForm.StepForm>
        </StepsForm>
        {/*<Divider style={{margin: '40px 0 24px'}}/>*/}
        {/*<div className={styles.desc}>*/}
        {/*  <h3>说明</h3>*/}
        {/*  <h4>认证说明</h4>*/}
        {/*  <p>*/}
        {/*    这里写一些认证说明*/}
        {/*  </p>*/}
        {/*</div>*/}
        <Modal
          visible={previewData.visible}
          title={previewData.title}
          footer={null}
          onCancel={
            () => {
              setPreviewData({image: "", title: "", visible: false})
            }
          }
        >
          <img alt="example" style={{width: '100%'}} src={previewData.image}/>
        </Modal>
      </Card>

      }
    </PageContainer>
  );
};

export default Approve;
